<template>
  <div class="flex h-full flex-col">
    <!-- 搜索和筛选区域 -->
    <div class="flex justify-between">
      <el-form :model="searchForm" inline label-width="80px">
        <el-form-item label="城市名称">
          <el-input v-model="searchForm.name" placeholder="请输入城市名称" clearable class="w-52" />
        </el-form-item>
        <el-form-item label="所属省份">
          <el-input
            v-model="searchForm.province_name"
            placeholder="请输入省份名称"
            clearable
            class="w-52"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable class="w-36">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="flex gap-3">
        <el-button type="primary" @click="handleCreate">新增城市</el-button>
        <el-button
          type="danger"
          @click="handleBatchDelete"
          :disabled="multipleSelection.length === 0"
        >
          批量删除
        </el-button>
      </div>
    </div>

    <!-- 城市列表 -->
    <div class="flex h-0 grow flex-col">
      <el-table
        class="grow"
        v-loading="loading"
        :data="cityList"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="城市名称" />
        <el-table-column prop="code" label="城市代码" />
        <el-table-column prop="province_name" label="所属省份" width="150" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="150"> </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" show-overflow-tooltip />
        <el-table-column prop="updated_at" label="更新时间" width="180" show-overflow-tooltip />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)" class="mr-2">
              编辑
            </el-button>
            <el-button type="danger" link @click="handleDelete(scope.row.id)"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="mt-2 flex justify-end">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 城市表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditMode ? '编辑城市' : '新增城市'"
      width="500px"
      destroy-on-close
    >
      <el-form :model="cityForm" ref="cityFormRef" label-width="100px" :rules="formRules">
        <el-form-item label="城市名称" prop="name">
          <el-input v-model="cityForm.name" placeholder="请输入城市名称" maxlength="50" />
        </el-form-item>
        <el-form-item label="城市代码" prop="code">
          <el-input v-model="cityForm.code" placeholder="请输入城市代码" maxlength="20" />
        </el-form-item>
        <el-form-item label="所属省份" prop="province_name">
          <el-input v-model="cityForm.province_name" placeholder="请输入省份名称" maxlength="50" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="cityForm.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number
            controls-position="right"
            v-model="cityForm.sort"
            :min="0"
            :max="999"
            placeholder="请输入排序值"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="flex justify-end space-x-2">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'

import { batchDeleteCity, createCity, deleteCity, getCityList, updateCity } from '@/api/system/city'
import { to } from '@/utils/promise'

// 表格数据相关
const loading = ref(false)
const cityList = ref<CityInfo[]>([])
const multipleSelection = ref<CityInfo[]>([])

// 搜索表单
const searchForm = reactive<{
  name: string
  province_name: string
  status: number | null
}>({
  name: '',
  province_name: '',
  status: null
})

// 分页信息
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const isEditMode = ref(false)
const cityFormRef = ref()
const cityForm = reactive<CityCreateData & { id?: number }>({
  name: '',
  code: '',
  province_name: '',
  status: 1,
  sort: 0
})

// 表单验证规则
const formRules = reactive({
  name: [
    { required: true, message: '请输入城市名称', trigger: 'blur' },
    { min: 1, max: 50, message: '城市名称长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入城市代码', trigger: 'blur' },
    { min: 1, max: 20, message: '城市代码长度在 1 到 20 个字符', trigger: 'blur' }
  ],
  province_name: [
    { required: true, message: '请输入所属省份', trigger: 'blur' },
    { min: 1, max: 50, message: '省份名称长度在 1 到 50 个字符', trigger: 'blur' }
  ]
})

// 初始化
onMounted(() => {
  fetchCityList()
})

// 获取城市列表
const fetchCityList = async () => {
  loading.value = true
  const params: CityQueryParams = {
    page: pagination.page,
    page_size: pagination.pageSize,
    name: searchForm.name,
    province_name: searchForm.province_name,
    status: searchForm.status || undefined
  }
  const [error, response] = await to(getCityList(params))
  if (error || !response) {
    ElMessage.error('获取城市列表失败')
    return
  }
  cityList.value = response.list || []
  pagination.total = response.total || 0
  loading.value = false
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchCityList()
}

// 重置
const handleReset = () => {
  searchForm.name = ''
  searchForm.province_name = ''
  searchForm.status = null
  pagination.page = 1
  fetchCityList()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchCityList()
}

const handleCurrentChange = (current: number) => {
  pagination.page = current
  fetchCityList()
}

// 选择变化
const handleSelectionChange = (val: CityInfo[]) => {
  multipleSelection.value = val
}

// 打开新增对话框
const handleCreate = () => {
  isEditMode.value = false
  Object.assign(cityForm, {
    id: undefined,
    name: '',
    code: '',
    province_name: '',
    status: 1,
    sort: 0
  })
  dialogVisible.value = true
}

// 打开编辑对话框
const handleEdit = (row: CityInfo) => {
  isEditMode.value = true
  Object.assign(cityForm, {
    id: row.id,
    name: row.name,
    code: row.code || '',
    province_name: row.province_name || '',
    status: row.status,
    sort: row.sort
  })
  dialogVisible.value = true
}

// 确认表单
const handleConfirm = async () => {
  if (!cityFormRef.value) return
  const [error] = await to(cityFormRef.value.validate())
  if (error) return
  if (isEditMode.value && cityForm.id) {
    const [error] = await to(updateCity(cityForm.id, cityForm))
    if (error) return
    ElMessage.success('编辑成功')
  } else {
    const [error] = await to(createCity(cityForm))
    if (error) return
    ElMessage.success('创建成功')
  }
  dialogVisible.value = false
  fetchCityList()
}

// 删除单个城市
const handleDelete = (id: number) => {
  ElMessageBox.confirm('确定要删除该城市吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const [error] = await to(deleteCity(id))
    if (error) return
    ElMessage.success('删除成功')
    fetchCityList()
  })
}

// 批量删除
const handleBatchDelete = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的城市')
    return
  }
  const ids = multipleSelection.value.map((item) => item.id)
  ElMessageBox.confirm(`确定要删除选中的 ${ids.length} 个城市吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const [error] = await to(batchDeleteCity({ ids }))
    if (error) return
    ElMessage.success('批量删除成功')
    fetchCityList()
    multipleSelection.value = []
  })
}

// 状态改变
const handleStatusChange = async (row: CityInfo) => {
  const [error] = await to(
    updateCity(row.id, {
      status: row.status === 1 ? 1 : 0,
      sort: row.sort
    } as CityUpdateData)
  )
  if (error) return
  ElMessage.success('状态更新成功')
  // 恢复原状态
  row.status = row.status === 1 ? 0 : 1
}

// 排序改变
const handleSortChange = async (row: CityInfo) => {
  const [error] = await to(
    updateCity(row.id, {
      sort: row.sort,
      status: row.status === 1 ? 1 : 0
    })
  )
  if (error) return
  ElMessage.success('排序更新成功')
  fetchCityList() // 重新获取数据以恢复原排序
}
</script>

<style scoped></style>
